package cn.thornbird.orgsync.repository.specification;

import cn.thornbird.orgsync.entity.User;
import cn.thornbird.orgsync.vo.request.UserQueryRequest;
import lombok.AllArgsConstructor;
import org.springframework.lang.NonNull;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@AllArgsConstructor
public class UserSpecification extends BaseSpecification<User> {

    private static final long serialVersionUID = -1817736537862246346L;

    private final UserQueryRequest userQueryRequest;

    @Override
    public Predicate toPredicate(@NonNull Root<User> root, @NonNull CriteriaQuery<?> query,
                                 @NonNull CriteriaBuilder criteriaBuilder) {
        List<Predicate> predicates = new ArrayList<>();
        List<String> fields = Arrays.asList("username", "name", "company", "title", "email", "mobile", "telephone");
        predicates.add(toKeywordPredicate(userQueryRequest.getKeyword(), fields, root, criteriaBuilder));
        predicates.add(createEqualPredicate(root, criteriaBuilder, "active", userQueryRequest.getActive()));
        predicates.add(createEqualPredicate(root, criteriaBuilder, "locked", userQueryRequest.getLocked()));
        predicates.add(createEqualPredicate(root, criteriaBuilder, "superuser", userQueryRequest.getSuperuser()));
        Predicate predicate = null;
        if (userQueryRequest.getType() != null) {
            predicate = criteriaBuilder.equal(root.get("type"), userQueryRequest.getType());
        }
        predicates.add(predicate);
        return toPredicate(criteriaBuilder, predicates);
    }

}
